#!/bin/bash
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#

SEUTIL_OUT="/tmp/seutil.out"
# Try reading SCM EEPROM first. This might fail on RHS SCM cards
# that are pre-DVT2
weutil /sys/class/i2c-adapter/i2c-0/0-0052/eeprom 2&>1 > ${SEUTIL_OUT}
if [ $? -eq 0 ]; then
  cat ${SEUTIL_OUT}
  exit 0
fi

((scm_logical_id=$(i2cget -f -y 12 0x31 0x3 2> /dev/null | head -n 1)))
((left=$(i2cget -f -y 12 0x31 0x5 2> /dev/null | head -n 1)))
((card_ver=$(i2cget -f -y 12 0x31 0x0 2> /dev/null | head -n 1)))
card_ver=$(($card_ver % 16))
# For right side cards fall back to getting this info from Left side card
# since pre DVT2 cards did not have EEPROM on right
if [ $scm_logical_id -lt 8 -a $left -ne 0 ]; then
  # right BMC
  ((slot_id=$(cat /sys/class/i2c-adapter/i2c-12/12-0031/slotid)))
  slot_id=$(($slot_id - 1))
  cat <<EOF > /tmp/seutil.py
import os,json,sys
for k,v in json.loads(sys.stdin.read())['Information'].items():
  if k.lower() == 'Location on Fabric'.lower():
    v = 'RIGHT'
  print "%s: %s" % (k, v)
EOF
  wget -qO- http://[fe80::${slot_id}:1%eth0.4088]:8080/api/sys/mb/seutil | python /tmp/seutil.py
else
  cat ${SEUTIL_OUT}
fi
